<script setup lang="ts">
import {ref} from "vue";
import type {AddressInfo} from "@/interfaces/user";
import {useGetUserAddressApi} from "@/services/api";
import {useStore} from "vuex";
import {onShow, onUnload} from "@dcloudio/uni-app";

const addressList = ref<AddressInfo[]>([])
const store = useStore()
const edit = (address: AddressInfo) => {
  uni.$u.route({
    url: '/pages/mine/editAddress',
    params: {
      data: JSON.stringify(address)
    }
  })
}
const add = () => {
  uni.$u.route({
    url: '/pages/mine/editAddress'
  })
}
const init = async () => {
  const {data: res} = await useGetUserAddressApi({userId: store.getters["auth/getUserId"]})
  addressList.value = res.addressList.map((value: AddressInfo) => {
    if (res.defaultId == value.id) {
      value.isDefault = 1
      return value
    } else {
      return value
    }
  }) || []
}
onShow(() => {
  init()
  uni.$on('init', () => init())
})
onUnload(() => {
  uni.$off('init')
})
</script>

<template>
  <view class="container">
    <view class="list">
      <view
          v-for="(address,index) in addressList"
          :key="index"
          class="address-item"
      >
        <view class="address">{{ address.address }}</view>
        <view class="people">
          <view class="name">{{ address.name }}</view>
          <view class="phone">{{ address.phone }}</view>
          <view v-if="address.isDefault" class="tag">
            <u-tag size="mini" text="默认" type="error"></u-tag>
          </view>
        </view>
        <view class="edit" @tap="edit(address)">
          <u-icon name="edit-pen" size="44"></u-icon>
        </view>
      </view>
    </view>
    <view class="add-btn">
      <u-button text="新建地址" type="error" @click="add"></u-button>
    </view>
  </view>
</template>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  background-color: #e9f3ff;
  padding: 12px;
  gap: 12px;

  .list {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    gap: 12px;

    .address-item {
      background-color: #ffffff;
      border-radius: 12px;
      padding: 12px;
      display: flex;
      flex-direction: column;
      gap: 8px;
      justify-content: center;
      position: relative;

      .region {
        font-size: 12px;
        color: #999999;
      }

      .address {
        font-size: 16px;
      }

      .people {
        display: flex;
        flex-direction: row;
        gap: 8px;
        font-size: 12px;

        .name {
          color: #000000;
        }

        .phone {
          color: #999999;
        }
      }

      .edit {
        position: absolute;
        top: calc(50% - 22rpx);
        right: 12px;
      }
    }
  }

  .add-btn {
    position: sticky;
    bottom: 3%;
    width: 100%;
  }
}
</style>